<!--
 * @Author: xiaotiwen
 * @Date: 2020-05-08 16:38:36
 * @LastEditTime: 2020-07-20 16:19:03
 * @LastEditors: xiaotiwen
 * @FilePath: \eduweb\src\views\practiceManagement\practiceTask\index.vue
 * @Description: 实习任务分班
 -->
<template>
    <div>
        <ConditionCard shadow="never" label-width="120px" @search="onSubmit" @reset="reset('queryForm')">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="$t('label.schoolTerm')">
                            <CalendarSelect v-model="queryForm.yearTerm" @load-done="loadDone"></CalendarSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.grade')">
                            <el-date-picker v-model="queryForm.grade" value-format="yyyy" type="year" :placeholder="$t('message.plzSelect')" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.trainingLevel')">
                            <DictSelect v-model="queryForm.trainingLevel" :data="options.trainingLevel" :clearable="false" :disabled="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="$t('fundingManagement.label.courseOpenAcademy')">
                            <DictSelect
                                v-model="queryForm.courseOpenAcademyId"
                                :data="options.courseOpenAcademyId"
                                :clearable="false"
                                :filterable="true"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('courseConfirmation.label.stuFaculty')">
                            <DictSelect v-model="queryForm.studentAcademyId" :data="options.studentAcademyId" :clearable="false" :filterable="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.major')">
                            <MyMajor :faculty="queryForm.studentAcademyId" :grade="queryForm.grade" v-model="queryForm.majorId"> </MyMajor>
                        </el-form-item>
                    </el-col>
                </el-row>
        </ConditionCard>
        <el-card shadow="never" body-style="padding: 24px;">
            <h2 class="titles">{{$t('arrCourse.title.listTitle')}}</h2>
            <div class="edu-opertion-bar">
                <div class="float-left">
                    <KeywordInput v-model="queryForm.course" :placeholder="$t('courseConfirmation.tips.keyTips')" @enter="handSearchChang"></KeywordInput>
                    <!-- <el-input style="width: 200px;" v-model="queryForm.course" maxlength="30" :placeholder="$t('courseConfirmation.tips.keyTips')" prefix-icon="el-icon-search" @change.entry.native="handSearchChang" /> -->
                </div>
                <div class="float-right">
                    <el-button type="primary" @click="handleExportSchemes">{{$t('message.export')}}</el-button>
                    <el-button v-if="menuAuths.cancelMerge" type="danger" @click="unmerge">{{$t('practiceTask.btn.cancelMerge')}}</el-button>
                    <el-button v-if="menuAuths.mergeCourse" type="primary" @click="merge">{{$t('practiceTask.btn.mergeCourse')}}</el-button>
                </div>
            </div>
        </el-card>
        <el-table ref="tables" :data="data" @row-click="rowClick" @expand-change="zydescription" :row-class-name="setClassName" :row-key="getRowKeys" :expand-row-keys="expands" @row-dblclick="zydescription">
            <el-table-column width="30" type="expand">
                <template slot-scope="scope">
                    <div class="expandTable" style="width: calc(100% - 65px)">
                        <el-table :data="scope.row.children" ref="tables1" :show-header="false">
                            <el-table-column width="60"></el-table-column>
                            <el-table-column :min-width="item1.width" v-for="(item1, idx1) in label" :key="idx1" :align="item1.center?'center':''" :prop="idx1<=2&&idx1>0?'test':item1.props" show-overflow-tooltip></el-table-column>
                        </el-table>
                    </div>
                </template>
            </el-table-column>
            <el-table-column width="30" type="selection" fixed="left"></el-table-column>
            <el-table-column width="50" align="center" type="index" fixed="left" :index="indexMethod" :label="$t('message.order')"></el-table-column>
            <el-table-column :min-width="item.width" :align="item.center?'center':''" v-for="(item, idx) in label" :label="item.label" :key="item.props" :prop="item.props" :sortable="item.sortable" show-overflow-tooltip :fixed="item.fixed"></el-table-column>
            <el-table-column width="120" align="center" :label="$t('message.operating')" fixed="right">
                <template slot-scope="scope">
                    <div class="opreate" @click.stop="">
                        <el-button type="text" v-if="menuAuths.divide&&scope.row.isPlace==='N'" @click="separate(scope.row, 'divide')">{{$t('practiceTask.btn.divide')}}</el-button>
                        <el-button type="text" v-else-if="menuAuths.disDivide" @click="separate(scope.row, 'disDivide')">{{$t('practiceTask.btn.disDivide')}}</el-button>
                        <el-button type="text" @click="lookDetails(scope.row)" v-if="scope.row.isPlace==='Y'">{{$t('message.detail')}}</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="edu-pagination">
            <div class="float-right">
                <el-pagination :current-page="page.pageNum_" :page-sizes="[20,50,100,500,1000]" :page-size="page.pageSize_" :total="page.total" layout="total, sizes, prev, pager, next, jumper" style="float: right;margin:0;" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
        <!-- 详情 -->
        <el-dialog :title="$t('practiceTask.title.detailTitle')" :visible="detailVisible" @close="detailVisible = false" width="926px" :close-on-click-modal="false">
            <practiceTaskDetails ref="details" :detailsId="ids" v-if="detailVisible"></practiceTaskDetails>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false">{{ $t('message.return') }}</el-button>
            </span>
        </el-dialog>
        <!-- 分班 -->
        <el-dialog :title="$t('practiceTask.title.editTitle')" :visible="separateVisible" @close="separateVisible = false" width="926px" :close-on-click-modal="false">
            <divide ref="divide" :ids="ids" v-if="separateVisible"></divide>
            <span slot="footer" class="dialog-footer">
                <el-button @click="separateVisible = false">{{ $t('message.cancel') }}</el-button>
                <el-button @click="sendData" type="primary" >
                    {{ $t('message.submit') }}
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { findDept } from 'common/src/api/user'
import practiceTaskDetails from './practiceTaskDetails';
import commonMixins from '../commonMixins';
import divide from './divide';
import { getList, listDdetails, unionCourses, cancelUnion, cancelDdivide, divideClass, exportData, getSettingTime, isSchedule } from "common/src/api/practiceManagement/practiceTask";
import MyMajor from "common/src/views/practiceManagement/common/MyMajor";
export default {
    // 组件名称
    name: 'practiceTask',
    mixins: [commonMixins],
    // 局部注册的组件
    components: {
        practiceTaskDetails,
        divide,
        MyMajor
    },
    // 组件参数 接收来自父组件的数据
    props: {},
    // 组件状态值
    data() {
        return {
            detailVisible: false,
            separateVisible: false,
            yearTerms: '',
            searchYearTerm: '',
            ids: '',
            page: {
                pageNum_: 1,
                pageSize_: 20,
                total: 0
            },
            getRowKeys(row) {
                return row.id;
            },
            expands: [],
            data: [],
            label: [
                { label: this.$t('label.grade'), props: 'grade', width: 90, sortable: true },
                { label: this.$t('fundingManagement.label.courseCode'), props: 'courseCode', width: 100, sortable: true, fixed: "left" },
                { label: this.$t('fundingManagement.label.courseName'), props: 'courseName', width: 130, sortable: true, fixed: "left" },
                { label: this.$t('label.openClassCollege'), props: 'courseOpenAcademy', width: 180, sortable: true },
                { label: this.$t('courseConfirmation.label.stuFaculty'), props: 'studentAcademy', width: 180, sortable: true },
                { label: this.$t('label.major'), props: 'majorName', width: 180, sortable: true },
                { label: this.$t('label.trainingLevel'), props: 'trainingLevels', width: 100, sortable: false },
                { label: this.$t('courseConfirmation.label.planWeeks'), props: 'weeks', width: 100, sortable: true },
                { label: this.$t('courseConfirmation.label.confirmWeeks'), props: 'confirmWeeks', width: 100, sortable: true },
                { label: this.$t('courseConfirmation.label.planCount'), props: 'planCount', width: 100, sortable: true },
                { label: this.$t('courseConfirmation.label.confirmCount'), props: 'confirmCount', width: 120, sortable: true }
            ],
            queryForm: {
                yearTerm: '', // 学年学期
                grade: '', // 年级
                trainingLevel: 'UDG', // 培养层次
                studentAcademyId: '', // 学院院系
                courseOpenAcademyId:'',//开课学院
                majorId: '', // 专业
                course: '' // 课程代码或名称
            },
            // 下拉相关选项数据
            options: {
                trainingLevel: [{ label: this.$t('courseConfirmation.udg'), value: 'UDG' }, { label: this.$t('courseConfirmation.pre'), value: 'asdf' }], // 培养层次
                studentAcademyId: [], // 学院院系
                courseOpenAcademyId:[],//开课学院
                majorId: [] // 专业
            },
            auths: [],
            menuAuths: {
                disDivide: false,
                divide: false,
                mergeCourse:false,
                cancelMerge:false
            }
        };
    },
    // 计算属性
    computed: {

    },
    // 侦听器
    watch: {
        auths: {
            handler(newVal) {
                if (newVal && Array.isArray(newVal) && newVal.length > 0) {
                    newVal.some(item => {
                        if(item.authCode === 'practiceTask-disDivide'){
                            this.menuAuths.disDivide = true
                        }
                        if(item.authCode === 'practiceTask-divide'){
                            this.menuAuths.divide = true
                        }
                        if(item.authCode === 'practiceTask-mergeCourse'){
                            this.menuAuths.mergeCourse = true
                        }
                        if(item.authCode === 'practiceTask-cancelMerge'){
                            this.menuAuths.cancelMerge = true
                        }
                    })
                }
            }
        }
    },
    /**
    * 在实例初始化之后，组件属性计算之前，如data属性等
    */
    created() {
        this.auths = JSON.parse(localStorage.getItem('sessiondata')).auths
    },
    /**
    * 在挂载开始之前被调用：相关的 render 函数首次被调用。
    */
    mounted() {
        let param = {
            X_YX: 'courseOpenAcademyId' // 学院
        };
        this.initOptions(param);
        findDept(0).then(res => {
            if (res.code == 200 && res.data) {
                this.options.studentAcademyId = res.data.map(row => {
                    return { label: row.deptName, value: row.deptCode }
                })
            }
        })
    },
    // 组件方法
    methods: {
        separate(row, type) { // type divide分班，disDivide取消分班
             this.timeSetBtns(row.yearTerm).then(res => {
                if (!res) {
                    return;
                }else{
                    let param = { id: row.id };
                    if (type === 'divide') { // 分班
                        this.separateVisible = true;
                        this.ids = row.id;
                        this.$nextTick(() => {
                            this.$refs.divide.getDetails();
                        });
                    } else { // 取消分班
                        isSchedule({ id: row.id }).then(res => {
                            if (res && res.code !== 200) {
                                this.$message({ message: res.msg, type: 'warning' });
                                return;
                            }
                            if (res.data === 'Y') {
                                this.getSettingTime().then(res1 => {
                                    if (res1) {
                                        this.$confirm(this.$t('practiceTask.tips.confirmOperation'), this.$t('message.prompt'), {
                                            confirmButtonText: this.$t('message.confirm'),
                                            cancelButtonText: this.$t('message.cancel'),
                                            type: "warning"
                                        }).then(() => {
                                            cancelDdivide(param).then(res => {
                                                if (res && res.code !== 200) {
                                                    this.$message({ message: res.msg, type: 'warning' });
                                                    return;
                                                }
                                                this.getLists(false);
                                                this.$message({ type: 'success', message: this.$t('practiceTask.tips.cancelSuccess') });
                                            });
                                        });
                                    } else {
                                        this.$message({ type: 'warning', message: this.$t('practiceTask.tips.cannotCancel') })
                                    }
                                })
                            } else {
                                this.$confirm(this.$t('practiceTask.tips.cancelTips'), this.$t('message.prompt'), {
                                    confirmButtonText: this.$t('message.confirm'),
                                    cancelButtonText: this.$t('message.cancel'),
                                    type: 'warning'
                                }).then(actions => {
                                    cancelDdivide(param).then(res => {
                                        if (res && res.code !== 200) {
                                            this.$message({ message: res.msg, type: 'warning' });
                                            return;
                                        }
                                        this.getLists(false);
                                        this.$message({ type: 'success', message: this.$t('practiceTask.tips.cancelSuccess') });
                                    });
                                })
                            }
                        })

                    }

                }
            })
        },
        sendData() { // 分班提交
            let datas = this.$refs.divide.getData(this.queryForm.yearTerm);
            if (datas) {
                let jsonData = {
                    id: this.ids,
                    udgPtClassInfos: datas.children,
                    courseCode:datas.children[0].courseCode
                };
                divideClass(jsonData).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.getLists(false);
                    this.$message({ message: this.$t('practiceTask.tips.divideSuccess'), type: 'warning' });
                    this.separateVisible = false;
                });
            }
        },
        lookDetails(row) { // 查看详情
            this.detailVisible = true;
            this.ids = row.id;
            this.$nextTick(() => {
                this.$refs.details.getDetails();
            });
        },
        zydescription(row) { // 获取展开数据
            let param = {
                'id': row.id
            };
            if (this.expands.length > 0 && this.expands[0] === row.id) {
                this.expands = [];
                return;
            } else if (row.mergeFlag === 'N' || !row.mergeFlag) {
                return;
            } else if (!row.hasOwnProperty('children')) {
                listDdetails(param).then(res => {
                    if (res.data.length > 0) {
                        this.$set(row, 'children', res.data);
                        this.expands = [row.id];
                    }
                });
            } else if (row.hasOwnProperty('children')) {
                this.expands = [row.id];
            }
        },
        setClassName({ row }) { // 是否有展开项
            return row.mergeFlag !== 'Y' ? 'unexpand' : '';
        },
        rowClick(row) { // 单项选择
            this.$refs.tables.toggleRowSelection(row);
        },
        merge() { // 合并课程
            let jsons = this.$refs.tables.selection;
            if (jsons.length <= 1) {
                this.$noSelectAlert(this.$t('practiceTask.tips.atLeastTwo'));
                return;
            }
            let flag = jsons.some(item => {
                return item.isPlace === 'Y' || !item.isPlace;
            });
            if (flag) {
                this.$noSelectAlert(this.$t('practiceTask.tips.cannotMerge'));
                return;
            }
            let code = jsons[0].courseCode;
            let flag1 = jsons.some(item => {
                return item.courseCode !== code;
            });
            if (flag1) {
                this.$noSelectAlert(this.$t('practiceTask.tips.cannotMerge2'));
                return;
            }
            let jsonData = [];
            let flags = false;
            jsons.forEach(item => {
                if (item.mergeFlag === 'Y') {
                    flags = true;
                    return;
                }
                jsonData.push({ id: item.id });
            });
            if (flags) {
                this.$noSelectAlert(this.$t('practiceTask.tips.already'));
                return;
            }
            this.$confirm(this.$t('practiceTask.tips.confirmMerge'), this.$t('message.prompt'), {
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel'),
                type: 'warning'
            }).then(() => {
                unionCourses(jsonData).then((res) => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.getLists(true);
                    this.$message({ type: 'success', message: this.$t('practiceTask.tips.mergeSuccess') });
                });
            })
        },
        unmerge() { // 取消合并课程
            let jsons = this.$refs.tables.selection;
            if (jsons.length === 0) {
                this.$noSelectAlert();
                return;
            } else if (jsons.length > 1) {
                this.$noSelectAlert(this.$t('practiceTask.tips.onlyOne'));
                return;
            }
            if (jsons[0].mergeFlag !== 'Y') {
                this.$noSelectAlert(this.$t('practiceTask.tips.plzMerge'));
                return;
            }
             this.$confirm(this.$t('practiceTask.tips.cancelMerge'), this.$t('message.prompt'), {
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel'),
                type: 'warning'
            }).then(() => {
                let jsonData = {
                    id: jsons[0].id
                };
                cancelUnion(jsonData).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.getLists(true);
                    this.$message({ type: 'success', message: res.msg });
                });
            });
        },
        handleSizeChange(val) { // 分页数量事件
            this.$set(this.page, 'pageSize_', val);
            this.getLists();
        },
        handleCurrentChange(val) { // 分页当前页事件
            this.$set(this.page, 'pageNum_', val);
            this.getLists();
        },
        handSearchChang() { // 搜索
            this.getLists(true);
        },
        reset(ids) { // 重置
            // this.$refs.queryForm.resetFields();
            for (const key in this.queryForm) {
                if (key !== 'yearTerm') {
                    this.queryForm[key] = '';
                }
            }
            this.queryForm.yearTerm = this.yearTerms;
            this.queryForm.trainingLevel = 'UDG';
            this.getLists(true);
        },
        onSubmit() { // 筛选
            this.getLists(true);
        },
        getLists(refresh) { // 获取数据
            if(refresh){
                this.page.pageNum_ = 1
            }
            this.expands = [];
            let jsons = {
                condition: this.queryForm,
                pageNum_: this.page.pageNum_,
                pageSize_: this.page.pageSize_
            };
            this.searchYearTerm = this.queryForm.yearTerm;
            getList(jsons).then(res => {
                this.data = res.data.list;
                this.data.forEach(item => {
                    if (item.trainingLevel === 'UDG') {
                        this.$set(item, 'trainingLevels',  this.$t('courseConfirmation.udg'));
                    }
                })
                this.page.total = res.data.total_;
            });
        },
        loadDone() { // 页面加载时保存学期学年
            this.yearTerms = this.queryForm.yearTerm;
            this.searchYearTerm = this.queryForm.yearTerm;
            this.getLists();
        },
        handleExportSchemes(type) { // 导出
            let selection = this.$refs.tables.selection;
            let params = {
                exportType: 0,
                request: this.queryForm,
                responses: null
            }
            if (selection.length > 0) {
                params.exportType = 1;
                selection.forEach(item =>{
                    item.trainingLevel = '本科'
                })
                params.responses = selection
            }
            exportData(params);
        },
        getSettingTime() {
            let status = false;
            return new Promise((resolve) => {
                getSettingTime({ yearTerm: this.searchYearTerm }).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    let nows = new Date().getTime();
                    let startTime = 0;
                    let endTime = 0;
                    if (res.data.cosArrangeStartDate) {
                        startTime = new Date(res.data.cosArrangeStartDate).getTime();
                    }
                    if (res.data.cosArrangeEndDate) {
                        endTime = new Date(res.data.cosArrangeEndDate).getTime();
                    }
                    let flag1 = nows - startTime > 0 ? true : false;
                    let flag2 = endTime - nows > 0 || endTime === 0 ? true : false;
                    if (flag1 && flag2) {
                        status = true;
                    }
                    resolve(status);
                }).catch(() => {
                    resolve(status);
                })
            });
        },
        indexMethod(index) {
          return (this.page.pageNum_ - 1) * this.page.pageSize_ + index + 1;
        }
    }
};
</script>
<style lang="scss" scoped>
.expandTable {
    ::v-deep td {
        border: none;
    }
    .el-table::before {
        width: 0;
        height: 0;
    }
}
.opreate {
    display: flex;
    justify-content: space-between;
}
::v-deep.unexpand .el-table__expand-column .cell {
    display: none;
}
.titles {
    font-weight: bold;
    color: #2b3b4e;
}
</style>
